package com.hotelManager.www.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.io.InputStream;
import java.util.Properties;

public class JDBCUtils {
    public static Connection getConnection() throws Exception {
        Connection conn;
        
        try {
            // 从properties文件读取配置
            Properties properties = new Properties();
            try (InputStream input = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties")) {
                if (input == null) {
                    throw new RuntimeException("无法找到 jdbc.properties 文件");
                }
                properties.load(input);
            }

            String driver = properties.getProperty("jdbc.driver");
            String url = properties.getProperty("jdbc.url");
            String username = properties.getProperty("jdbc.username");
            String password = properties.getProperty("jdbc.password");

            System.out.println("正在加载数据库驱动: " + driver);
            Class.forName(driver);
            System.out.println("数据库驱动加载成功");

            System.out.println("正在连接数据库: " + url);
            conn = DriverManager.getConnection(url, username, password);
            System.out.println("数据库连接成功！");
        } catch (ClassNotFoundException e) {
            System.err.println("数据库驱动加载失败: " + e.getMessage());
            throw new Exception("数据库驱动加载失败: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("数据库连接失败: " + e.getMessage());
            throw new Exception("数据库连接失败: " + e.getMessage());
        }
        return conn;
    }

    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
                System.out.println("数据库连接已关闭");
            } catch (Exception e) {
                System.err.println("关闭数据库连接失败: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
    
    
    
}
